import { defineStore } from 'pinia'
import { ref } from 'vue'
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import { routers,asnyrouter} from '@/router/router.ts'
// import type { RouteRecordRaw } from 'vue-router'
import router from '@/router/index.ts'

export const useUserstore = defineStore(
  'user',
  () => {
    const userInfo = ref({
      token: '',
      avatar: '',
      name: '',
      menuRouter:routers,
      buttons:[] as any
    })
      function filterAsyncRoute(asnycRoute: any, routes: any) {
          return asnycRoute.filter((item: any) => {
              if (routes.includes(item.name)) {
                  if (item.children && item.children.length > 0) {
                      //硅谷333账号:product\trademark\attr\sku
                      item.children = filterAsyncRoute(item.children, routes)
                  }
                  return true
              }
          })
      }
    const setuserInfo = async (username: string, password: string) => {
      const p = await reqLogin({ username, password })
      if (p.code === 200) {
        userInfo.value.token = p.data
        return 'ok'
      } else {
        return Promise.reject(new Error(p.data))
      }
    }
    const useUserInfo = async () => {
      const p = await reqUserInfo()
      if (p.code === 200) {
        userInfo.value.avatar = p.data.avatar
        userInfo.value.name = p.data.name
        userInfo.value.buttons = p.data.buttons
          const userAsyncRoute = filterAsyncRoute(
              cloneDeep(asnyrouter),
              p.data.routes,
          )
          //菜单需要的数据整理完毕
          userInfo.value.menuRouter = [...routers, ...userAsyncRoute]
          //目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
          ;[...userAsyncRoute].forEach((route: any) => {
              router.addRoute(route)
          })
      }
    }
    const Logout = async () => {
      userInfo.value = {
        token: '',
        avatar: '',
        name: '',
        menuRouter:[],
        buttons: []
      }
      const p = await reqLogout()
      if (p.code === 200) {
        return 'ok'
      } else {
        return Promise.reject(new Error('退出登录失败'))
      }
    }
    return {
      userInfo,
      setuserInfo,
      useUserInfo,
      Logout,
    }
  },
  { persist: true },
)
